const { ErrorModel, SuccessModel } = require('../utils/index')
const logger = require('../utils/logger')
const fs = require("fs")
const Busboy = require('busboy')
const csv = require('csvtojson')
const { DataCSVModel } = require("./../models/data_csv")
const { saveCSVFile } = require('../config')
class DataCSVController {
  /**
   * @description 添加CSV
   * @param {*} name
   * @param {*} path
   * @param {*} remark
   */
  static async dataCSVAdd (req, res, next) {
    const { name, path, remark, } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataCSVController`, `dataCSVAdd`, `req.body`, req.body)
    if (!path) {
      res.json(new ErrorModel([], `缺少必填项`))
      return
    }
    try {
      const CSVInfo = await DataCSVModel.findByPath(path);
      if (CSVInfo) {
        res.json(new ErrorModel([], `当前CSV已存在`))
        return
      }
      const result = await DataCSVModel.create(name, path, remark, op_user_id,)
      logger.info(`DataCSVController`, `dataCSVAdd`, `result`, result)
      res.json(new SuccessModel([], `新增CSV成功`))
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 更新CSV
   * @param {*} data_csv_id
   * @param {*} name
   * @param {*} path
   * @param {*} remark
   */
  static async dataCSVUpd (req, res, next) {
    const {
      data_csv_id,
      name, path, remark,
    } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataCSVController`, `dataCSVUpd`, `req.body`, req.body)
    if (!data_csv_id || !path) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const CSVInfo = await DataCSVModel.findByPathAndId(path, id)
      if (CSVInfo) {
        res.json(new ErrorModel([], `CSV已存在`))
        return
      }
      const result = await DataCSVModel.update(name, path, remark, op_user_id, data_csv_id)
      logger.info(`DataCSVController`, `dataCSVUpd`, `result`, result)
      res.json(new SuccessModel([], `CSV更新成功`))
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除CSV
   * @param {*} data_csv_id
   */
  static async dataCSVDel (req, res, next) {
    const { data_csv_id } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`DataCSVController`, `dataCSVDel`, `req.body`, req.body)
    if (!data_csv_id) {
      res.json(new ErrorModel([], `data_csv_id 获取失败`))
      return
    }
    try {
      const CSVInfo = await DataCSVModel.findById(data_csv_id)
      if (CSVInfo) {
        const result = await DataCSVModel.delete(op_user_id, data_csv_id)
        fs.unlink(CSVInfo.path, (err) => {
          if (err) throw err;
          logger.info(`DataCSVController`, `dataCSVDel`, `result`, result)
          res.json(new SuccessModel([], `删除CSV成功`))
        })
      }
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description CSV分页列表
   * @param {*} data_csv_id
   */
  static async dataCSVList (req, res, next) {
    const {
      page,
      size = 1,
      name,
      remark,
    } = req.query
    logger.info(
      `DataCSVController`,
      `dataCSVList`,
      `req.query`,
      req.query
    )
    try {
      const { result, count } = await DataCSVModel.list(page, size, name, remark,)
      logger.info(`DataCSVController`, `dataCSVList`, `result`, result, count)
      res.json(new SuccessModel({ result, total: count[0].count, limit: Number(limit), size: Number(size) }, `获取CSV数据成功`))
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
    * @description CSV总列表
    * @param {*} data_csv_id
    */
  static async dataCSVAllList (req, res, next) {
    try {
      const result = await DataCSVModel.allList()
      logger.info(`DataCSVController`, `dataCSVAllList`, `result`, result,)
      res.json(new SuccessModel({ result, }, `获取CSV数据成功`))
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVAllList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 获取CSV数据
   * @param {*} data_csv_id
   */
  static async dataCSVByID (req, res, next) {
    const { data_csv_id } = req.body
    logger.info(`DataCSVController`, `dataCSVByID`, `req.body`, req.body)
    if (!data_csv_id) {
      res.json(new ErrorModel([], `查询失败,获取不到data_csv_id`))
      return
    }
    try {
      const CSVInfo = await DataCSVModel.findAllById(data_csv_id)
      if (!CSVInfo) {
        res.json(new ErrorModel([], `CSV不存在`))
        return
      }
      csv()
        .fromFile(CSVInfo.path)
        .then((jsonObj) => {
          logger.info(`DataCSVController`, `dataCSVByID`, `jsonObj`, jsonObj)
          res.json(new SuccessModel(jsonObj, `查询成功`))
        })
    } catch (error) {
      logger.error(`DataCSVController`, `dataCSVByID`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 上传CSV文件
   */
  static async dataCSVUpload (req, res, next) {
    const busboy = new Busboy({ headers: req.headers });
    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      file.pipe(fs.createWriteStream(saveCSVFile));
    });

    busboy.on('finish', function () {
      csv()
        .fromFile(saveCSVFile)
        .then((data) => {
          logger.info(`DataCSVController`, `dataCSVByID`, `data`, data)
          res.json(new SuccessModel({ result: data, path: saveCSVFile }, `上传成功`))
        })
    });
    return req.pipe(busboy);
  }
}

module.exports = {
  DataCSVController,
}
